package com.example.skincoredemo;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.skincoredemo.utils.GloablConfig;

import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * 集中管理App中所有的页面的生命周期。
 */
public class SkinActivityLifecycle implements Application.ActivityLifecycleCallbacks {

    HashMap<Activity, SkinLayoutFactory> factoryHashMap = new HashMap<>();

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
        Log.e(GloablConfig.LOG_TAG, "SkinActivityLifecycle onActivityCreated");
        // 获取Activity级别的布局加载器LayoutInflater
        LayoutInflater layoutInflater = LayoutInflater.from(activity);

        // 重置字段，防止报错
        try {
            Field factorySet = LayoutInflater.class.getDeclaredField("mFactorySet");
            factorySet.setAccessible(true);
            factorySet.setBoolean(layoutInflater, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加自定义创建View工程
        SkinLayoutFactory factory = new SkinLayoutFactory();
        layoutInflater.setFactory2(factory);
        // 注册观察者
        SkinManager.getInstance().addObserver(factory);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        // 删除观察者
        SkinLayoutFactory remove = factoryHashMap.remove(activity);
        SkinManager.getInstance().deleteObserver(remove);
    }
}
